﻿namespace RFIDStation.DeviceDriver.IModules.Impls;

public class RFIDUHFReaderModule : IModule
{
    private readonly ILogger _logger;
    private readonly ViewModel _viewModel;

    public RFIDUHFReaderModule( ILoggerFactory loggerFactory, ViewModel viewModel )
    {
        _logger = loggerFactory.CreateLogger( "超高频模块" );
        _viewModel = viewModel;
    }

    public async Task StartAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "uhf" ) return;

        var config = _viewModel.AppConfig.RFIDReaderList.First( );
        if ( config.Enable is false ) return;

        _viewModel.RFIDUHFReader = new Dev.Integration.UHFReader.ApiClientBuilder( )
                                                                .UseReaderKind( config.Kind )
                                                                .UseReaderConfig( o =>
                                                                {
                                                                    o.Connect.ConnectType = config.ConnectType;
                                                                    o.Connect.ConnectArgs = config.ConnectArgs;
#if DEBUG
                                                                    o.MonitorLogAction = log => ConsoleWirter.Debug( $"+ [{DateTime.Now}] [uhf] {log}" );
#endif
                                                                } )
                                                                .Build( );

        _viewModel.RFIDUHFReader.OnOpenedHandler = ( s, e ) =>
        {
            ConsoleWirter.Success( $"+ [uhf] {_viewModel.RFIDUHFReader.ReaderId} 连接成功" );
        };
        _viewModel.RFIDUHFReader.OnInventoryTagHandler = ( s, e ) =>
        {
            _viewModel.AddOrUpdateRFIDUHFTag( e.Tag );
            //ConsoleWirter.Debug( $"+ [uhf] epc: {e.Tag.EPC}, rssi: {e.Tag.RSSI}, tid: {e.Tag.TID}" );
        };


        // 重连机制
        _ = Task.Factory.StartNew( ( ) =>
        {
            while ( true )
            {
                try
                {
                    if ( _viewModel.RFIDUHFReader.ReaderState == Dev.Integration.UHFReader.Constants.ReaderState.Close )
                    {
                        _viewModel.RFIDUHFReader.Open( );
                    }
                }
                catch ( Exception ex )
                {
                    ConsoleWirter.Warning( $"+ [uhf] {_viewModel.RFIDUHFReader.Config.Connect.ConnectArgs} 连接失败: {ex.Message}" );
                }

                Thread.Sleep( 10 * 1000 );
            }
        } );

        await Task.CompletedTask;
    }

    public async Task StopAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "uhf" ) return;

        try
        {
            _viewModel.RFIDUHFReader.Close( );

            _logger.Info( $"注销成功. 读写器: {_viewModel.RFIDUHFReader.ReaderId}" );
        }
        catch ( Exception ex )
        {
            _logger.Warning( $"注销失败. 读写器: {_viewModel.RFIDUHFReader.ReaderId}{Environment.NewLine}error: {ex.Message}" );
        }

        await Task.CompletedTask;
    }
}
